<template>
  <el-dialog
    width="600px"
    :title="$t('task.setting.taskTypeSetting.flow.components.title20', {name: typeName})"
    @close="close"
    :visible.sync="isShow"
    append-to-body
    :close-on-click-modal='false'>
    <div class="template-upload-modal">
      <p class="template-upload-help-info">
        <i18n path="task.setting.taskTypeSetting.flow.components.title21" tag="span">
          <a place="link" target="_blank" :href="help_link">
            {{$t('task.setting.taskTypeSetting.flow.components.title22')}}
          </a>
        </i18n>
      </p>
      <div class="template-upload-content">
        <el-steps direction="vertical">
          <el-step status="process">
            <el-row type="flex" justify="space-between" slot="description">
              <p>{{$t('task.setting.taskTypeSetting.flow.components.title23')}}</p>
              <div>
                <a :href="templateUrl">{{$t('common.base.download')}}</a>
              </div>
            </el-row>
          </el-step>
          <el-step status="process">
            <template slot="description">
              <p>{{$t('task.setting.taskTypeSetting.flow.components.title24', {name: typeName})}}</p>
              <template v-if="internationalGray && type === 'reportSetting'">
                <div class="language-upload">
                  <p>简体中文：</p>
                  <el-upload
                    ref="upload"
                    class="upload-template"
                    accept=".xlsx,.xls"
                    action=""
                    :file-list="fileList"
                    :on-remove="removeFile"
                    :on-preview="handlePreview"
                    :before-upload="beforeUpload">
                    <el-button size="small" type="text" :disabled="pending">{{$t('common.base.clickForUploading')}}</el-button>
                    <div slot="tip" class="template-upload-tip">{{$t('task.setting.taskTypeSetting.flow.components.tip6')}}</div>
                  </el-upload>
                </div>
                <div class="language-upload">
                  <p>English：</p>
                    <el-upload
                    ref="enUpload"
                    class="upload-template"
                    accept=".xlsx,.xls"
                    action=""
                    :file-list="enFileList"
                    :on-remove="enRemoveFile"
                    :on-preview="enHandlePreview"
                    :before-upload="enbeforeUpload">
                    <el-button size="small" type="text" :disabled="pending">{{$t('common.base.clickForUploading')}}</el-button>
                    <div slot="tip" class="template-upload-tip">{{$t('task.setting.taskTypeSetting.flow.components.tip6')}}</div>
                  </el-upload>
                </div>
                <div class="language-upload">
                  <p>Русский：</p>
                  <el-upload
                    ref="ruUpload"
                    class="upload-template"
                    accept=".xlsx,.xls"
                    action=""
                    :file-list="ruFileList"
                    :on-remove="ruRemoveFile"
                    :on-preview="ruHandlePreview"
                    :before-upload="ruBeforeUpload">
                    <el-button size="small" type="text" :disabled="pending">{{$t('common.base.clickForUploading')}}</el-button>
                    <div slot="tip" class="template-upload-tip">{{$t('task.setting.taskTypeSetting.flow.components.tip6')}}</div>
                  </el-upload>
                </div>
              </template>
              <template v-else>
                <el-upload
                  ref="upload"
                  class="upload-template"
                  accept=".xlsx,.xls"
                  action=""
                  :file-list="fileList"
                  :on-remove="removeFile"
                  :on-preview="handlePreview"
                  :before-upload="beforeUpload">
                  <el-button size="small" type="primary" :disabled="pending">{{$t('common.base.clickForUploading')}}</el-button>
                  <div slot="tip" class="template-upload-tip">{{$t('task.setting.taskTypeSetting.flow.components.tip6')}}</div>
                </el-upload>
              </template>
              

            </template>
          </el-step>
        </el-steps>
      </div>
    </div>

    <template slot="footer">
      <el-button @click="close">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" :disabled="pending" :loading="pending" @click="submit">{{$t('common.base.makeSure')}}</el-button>
    </template>
  </el-dialog>
</template>

<script>
// api
import * as TaskApi from '@src/api/TaskApi.ts';
// util
import Uploader from '@src/util/uploader';
import { getRootWindowInitData } from '@src/util/window'
import i18n from '@src/locales'
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()

export default {
  name: 'template-upload-dialog',
  inject: ['taskFlowData'],
  props: {
    visiable: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    taskTypeId: {
      type: String,
      default: ''
    },
    reportSetting: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      internationalGray,
      pending: false,
      isShow: false,

      templates: [],
      fileResult: {},
      // 国际化临时处理方案
      enTemplates: [],
      ruTemplates: [],
    }
  },
  computed: {
    tenantType(){
      return getRootWindowInitData()?.tenantType
    },
    help_link(){
      let url = ''
      if(this.tenantType == 4) {
        url = 'https://publink-hz.feishu.cn/wiki/wikcn3o0yrgP1kfcEAArsGZaCTc'
      } else {
        url = 'https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/vcb3zddig31hb31h/ga1dtytt6zk6bgz8/zyy6kb3rwwaw7xmg.html'
      }
      return url
    },
    typeName() {
      return this.type === 'reportSetting' ? i18n.t('task.serviceReport') : i18n.t('task.print');
    },
    templateUrl() {
      return `/setting/taskType/getTemplateDic?typeId=${this.taskTypeId}`;
    },
    fileList() {
      return this.templates.map(item => {
        return {
          name: item.filename || item.name || item.fileName,
          url: item.url
        }
      })
    },
    enFileList() {
      return this.enTemplates.map(item => {
        return {
          name: item.filename || item.name || item.fileName,
          url: item.url
        }
      })
    },
    ruFileList() {
      return this.ruTemplates.map(item => {
        return {
          name: item.filename || item.name || item.fileName,
          url: item.url
        }
      })
    }
  },
  watch: {
    visiable(val) {
      this.isShow = val;
      if(this.type === 'reportSetting') {
        this.templates = this.reportSetting.templates || []
        this.enTemplates = this.reportSetting.templates_en || []
        this.ruTemplates = this.reportSetting.templates_ru || []
      } else {
        this.templates = this.taskFlowData.taskTypeConfig[this.type].templates || [];
      }
    }
  },
  methods: {
    close() {
      this.$emit('update:visiable', false);
    },
    removeFile() {
      this.fileResult = {};
      this.templates = []
    },
    enRemoveFile() {
      this.enTemplates = []
    },
    ruRemoveFile() {
      this.ruTemplates = []
    },
    enHandlePreview(file) {
      let id = this.enTemplates[0]?.id;
      if(!id) return;

      let a = document.createElement('a');
      a.download = file.name;
      a.href = `/files/download?fileId=${id}`;
      a.click();
    },
    ruHandlePreview(file) {
      let id = this.ruTemplates[0]?.id;
      if(!id) return;

      let a = document.createElement('a');
      a.download = file.name;
      a.href = `/files/download?fileId=${id}`;
      a.click();
    },
    enbeforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isLt1M) {
        this.$platform.notification({
          type: 'error',
          title: this.$t('task.setting.taskTypeSetting.flow.components.tip7')
        });
        return false;
      }

      Uploader.upload(file, '/files/upload').then((result) => {
        if (result.status != 0) {
          this.$platform.notification({
            type: 'error',
            title: `${result.message}`,
            duration: 1500,
          });

          return false;
        }

        this.enTemplates = [result.data];
      }).catch(err => {
        console.error(err);
      })
      return false;
    },
    ruBeforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isLt1M) {
        this.$platform.notification({
          type: 'error',
          title: this.$t('task.setting.taskTypeSetting.flow.components.tip7')
        });
        return false;
      }

      Uploader.upload(file, '/files/upload').then((result) => {
        if (result.status != 0) {
          this.$platform.notification({
            type: 'error',
            title: `${result.message}`,
            duration: 1500,
          });

          return false;
        }

        this.ruTemplates = [result.data];
      }).catch(err => {
        console.error(err);
      })
      return false;
    },
    /** 点击已上传文件 */
    handlePreview(file) {
      let id = this.templates[0]?.id;
      if(!id) return;

      let a = document.createElement('a');
      a.download = file.name;
      a.href = `/files/download?fileId=${id}`;
      a.click();

    },
    /**
     * 文件上传
     */
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isLt1M) {
        this.$platform.notification({
          type: 'error',
          title: this.$t('task.setting.taskTypeSetting.flow.components.tip7')
        });
        return false;
      }

      Uploader.upload(file, '/files/upload').then((result) => {
        if (result.status != 0) {
          this.$platform.notification({
            type: 'error',
            title: `${result.message}`,
            duration: 1500,
          });

          return false;
        }

        this.fileResult = result.data;
        this.templates = [result.data];
      }).catch(err => {
        console.error(err);
      })


      return false;
    },
    /**
     * 保存模板
     */
    async submit(){
      let templatesAttr = this.type === 'reportSetting' ? 'templates' : 'p_templates';
      let params = {
        typeId: this.taskTypeId,
        [templatesAttr]: this.templates.map(item => {
          return {
            id: item.id,
            filename: item.filename || item.fileName,
            url: item.url || item.ossUrl,
            fileSize: item.fileSize || item.fileSizeStr
          }
        })
      };
      // 国际化临时处理
      if(this.type === 'reportSetting') {
        params.templates_en = this.enTemplates.map(item => {
          return {
            id: item.id,
            filename: item.filename || item.fileName,
            url: item.url || item.ossUrl,
            fileSize: item.fileSize || item.fileSizeStr
          }
        });
        params.templates_ru = this.ruTemplates.map(item => {
          return {
            id: item.id,
            filename: item.filename || item.fileName,
            url: item.url || item.ossUrl,
            fileSize: item.fileSize || item.fileSizeStr
          }
        });
      }

      try {
        this.pending = true;

        if(this.type === 'reportSetting') {
          this.$emit('reportSettingSave', {'templates': params.templates}, params)
        } else {
          let res = await TaskApi.savePrintTemplate(params);
          if(res.status === 0) {
            this.taskFlowData.taskTypeConfig[this.type].templates = this.templates;
            this.$platform.notification({
              type: 'success',
              title: this.$t('task.setting.settingSuccess')
            });
          }
        }
        this.close();
      } catch (err) {
        console.error(err);
      } finally{
        this.pending = false;
      }

    }
  }
}
</script>
<style lang="scss" scoped>
.template-upload-modal{
    min-height: 240px;
    font-size: 14px;
    .template-upload-help-info{
        color: #666666;
    }

    .template-upload-content{
        color: #000000;
        p, a{
            margin-bottom: 12px;
            font-size: 14px;
        }
        .template-upload-tip{
            margin-top: 8px;
            font-size: 12px;
            color: #999999;
        }
        .upload-template{
            width: 334px;
        }
      .language-upload {
        display: flex;
        justify-content: flex-start;
        p {
          padding-top: 7px;
          width: 70px;
        }
      }
    }

    a{
        color: $color-primary;
        &:hover{
            text-decoration: underline;
        }
    }
}

/** element-ui style */
::v-deep .el-step__description{
    padding-right: 0;
}

</style>
